//===============================================================================
// Microsoft Architecture Strategy Team
// LitwareHR - SaaS Sample Application
//===============================================================================
// Copyright  Microsoft Corporation.  All rights reserved.
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE.
//===============================================================================
// The example companies, organizations, products, domain names,
// e-mail addresses, logos, people, places, and events depicted
// herein are fictitious.  No association with any real company,
// organization, product, domain name, email address, logo, person,
// places, or events is intended or should be inferred.
//===============================================================================



using System;
using System.Collections.Generic;
using LitwareHR.Portfolio.Gateways;

namespace LitwareHR.PrivateApp.Presenters.ConfigCusto
{
    public class ManageUserRolesPresenter
    {
        private IManageUserRolesView _view;

        public ManageUserRolesPresenter(IManageUserRolesView view)
        {
            _view = view;
        }

        public void OnViewLoaded(string tenantAlias, string username)
        {
            if (String.IsNullOrEmpty(tenantAlias))
                throw (new ArgumentNullException("tenantAlias"));

            if (String.IsNullOrEmpty(username))
                throw (new ArgumentNullException("username"));

            string[] roleNames = AuthenticationGateway.GetRoles(tenantAlias);
            _view.ShowAllRoles(roleNames);

            string[] roleNamesToSelect = AuthenticationGateway.GetRolesForUser(tenantAlias, username);
            _view.SelectUserRoles(roleNamesToSelect);
        }

        public void OnRoleSelectionChanged(string tenantAlias, string[] selectedRoles, string username)
        {
            string[] currentRoles = AuthenticationGateway.GetRolesForUser(tenantAlias, username);

            foreach (string role in selectedRoles)
            {
                // if list of current roles does not contain a newly selected role, then add it
                if (!new List<string>(currentRoles).Contains(role))
                    AuthenticationGateway.AddUserToRole(tenantAlias, username, role);
            }

            foreach (string role in currentRoles)
            {
                // if a role in the current role is not on the new list we need to remove it
                if (!new List<string>(selectedRoles).Contains(role))
                    AuthenticationGateway.RemoveUserFromRole(tenantAlias, username, role);
            }
        }
    }
}
